package service

import (
	"errors"
	"gorm.io/gorm"
	"server_cluster/common/tools"
	"server_cluster/http/http_config"
	"server_cluster/http/model"
	"server_cluster/http/pkg/random"
	"sync/atomic"
)

// AccountLogin 账号登陆
func (s *Service) AccountLogin(nickname, headImageUrl, UserName, passWord, ipAddr string, platform int32) (int64, string, error) {
	account, err := s.d.QueryAccountByUserName(UserName)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			hashKey := ""
			EncryptedPass := ""
			if platform == model.PlatformInternal && !http_config.GetConfig().DevEnv {
				return 0, "", err
			}
			account = &model.DbAccount{
				Uid:          s.BuildUid(),
				Nickname:     nickname,
				HeadImageUrl: headImageUrl,
				UserName:     UserName,
				Platform:     platform,
				HashKey:      hashKey,
				PassWord:     EncryptedPass,
			}
			_, err := s.d.InsertAccount(account)
			if err != nil {
				var isSuccess = false
				for i := 1; i < 3; i++ {
					account.Uid = s.BuildUid()
					_, err := s.d.InsertAccount(account)
					if err == nil {
						isSuccess = true
						break
					}
				}
				if !isSuccess {
					return 0, "", err
				}
			}
		} else {
			return 0, "", err
		}
	}
	if platform == model.PlatformInternal && !http_config.GetConfig().DevEnv {
		passCheck := tools.BuildPassword(passWord, account.HashKey)
		if passCheck == "" || passCheck != account.PassWord {
			return 0, "", errors.New("password not match")
		}
	}
	account.Nickname = nickname
	account.HeadImageUrl = headImageUrl
	account.Token = random.GetRandomStr(32)
	account.IpAddr = ipAddr
	err = s.d.UpdateAccount(account)
	if err != nil {
		return 0, "", err
	}
	return account.Uid, account.Token, nil
}

func (s *Service) AccountLoginInterNal(uid int64, token string) bool {
	account := new(model.DbAccount)
	account.Uid = uid
	account.Token = token
	return s.d.CheckAccountToken4Internal(uid, token)
}

func (s *Service) BuildUid() int64 {
	atomic.AddInt64(&s.AutoIncrementNum, 1)
	return int64(tools.MathRand(0, 999))*1000000 + tools.TimeNow()%1000*1000 + s.AutoIncrementNum%1000
}
